package com.easychat.utils;
import com.easychat.entity.constants.Constants;
import com.easychat.entity.enums.UserContactTypeEnum;
import com.easychat.exception.BusinessException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;


public class StringTools {

    public static void checkParam(Object param) {
        try {
            Field[] fields = param.getClass().getDeclaredFields();
            boolean notEmpty = false;
            for (Field field : fields) {
                String methodName = "get" + StringTools.upperCaseFirstLetter(field.getName());
                Method method = param.getClass().getMethod(methodName);
                Object object = method.invoke(param);
                if (object != null && object instanceof String && !StringTools.isEmpty(object.toString())
                        || object != null && !(object instanceof String)) {
                    notEmpty = true;
                    break;
                }
            }
            if (!notEmpty) {
                throw new BusinessException("多参数更新，删除，必须有非空条件");
            }
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("校验参数是否为空失败");
        }
    }

    public static String upperCaseFirstLetter(String field) {
        if (isEmpty(field)) {
            return field;
        }
        //如果第二个字母是大写，第一个字母不大写
        if (field.length() > 1 && Character.isUpperCase(field.charAt(1))) {
            return field;
        }
        return field.substring(0, 1).toUpperCase() + field.substring(1);
    }

    public static boolean isEmpty(String str) {
        if (null == str || "".equals(str) || "null".equals(str) || "\u0000".equals(str)) {
            return true;
        } else if ("".equals(str.trim())) {
            return true;
        }
        return false;
    }
    //是否是数字
    public static boolean isNumber(String str) {
        String checkNumber = "^[0-9]+$";
        if (null == str) {
            return false;
        }
        if (!str.matches(checkNumber)) {
            return false;
        }

        return true;
    }

    /**
     * 获取count位的userId
     * @return “U”开头表示是UserId
     */
    public static String getUserId(){
        return UserContactTypeEnum.USER.getPrefix() +getRandomNumber(Constants.LENGTH_11);
    }
    /**
     * 获取count位的群ID
     * @return “G”开头表示是群ID
     */
    public static String getGroupId(Integer count){
        return UserContactTypeEnum.GROUP.getPrefix() +getRandomNumber(count);
    }

    /**
     * 获取count位的数字
     */
    public static String getRandomNumber(Integer count){
        return RandomStringUtils.random(count,false,true);
    }
    /**
     * 获取count位的字母+数字 组合
     */
    public static String getRandomString(Integer count){
        return RandomStringUtils.random(count,true,true);
    }

    /**
     * MD5 对string加密
     * @param originString  需要加密的String
     * @return
     */
    public static String encodeMD5(String originString){
        return originString==null? null:DigestUtils.md5Hex(originString);
    }

    // 过滤html标签方法
    public static String cleanHtmlTag(String sendMessage) {
        if (StringTools.isEmpty(sendMessage)) {
            return sendMessage;
        }

        sendMessage = sendMessage.replace("<", "&lt;");
        sendMessage = sendMessage.replace(">", "&gt;");
        sendMessage = sendMessage.replace("\r\n", "<br>");
        sendMessage = sendMessage.replace("\n", "<br>");
        return  sendMessage;
    }

    //获取用户的sessionId  保证两人的会话id一致 唯一
    /*
     * 好友会话 张三：123 李四：456 sessionId： MD5（123+456）、
     * 群会话： 群主号直接MD5
     */
    public static String getChatSessionIdUser(String[] userIds) {
        Arrays.sort(userIds);
        return  encodeMD5(StringUtils.join(userIds, ""));
    }
    //获取 群 会话id
    public static String getChatSessionIdGroup(String groupId) {
        return  encodeMD5(groupId);
    }

    //获取文件名后缀
    public static String getFileSuffix(String fileName){
        if (isEmpty(fileName)){
            return null;
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }
}
